import {
	myRequest,
	myFileRequest,
	baseUrl
} from './api.js'
import {
	callback
} from './qrcode.js';
//工具
//获取手机定位
let gaoDeKey = '7277a24b0f32e0dace6157d671d24c32';
export const getAddress = (options, callback) => {
	if (options.loading) {
		uni.showLoading({
			title: "正在获取定位",
			mask: true
		})
	}
	const timer = setTimeout(() => {
		uni.hideLoading()
		// 函数执行超时，可以在这里进行相应的处理
		callback && callback.call(undefined, {
			longitude: "",
			latitude: "",
			address: "获取定位失败",
			locationMode: "手机定位",
			errCode: "200"
		})
	}, 6000);
	uni.getLocation({
		type: 'wgs84',
		geocode: false,
		success: function(res) {
			//经纬度
			let longitude = res.longitude;
			let latitude = res.latitude;
			let locationMode = "手机定位";
			let speed = res.speed
			if (longitude && latitude) {
				uni.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?key=${gaoDeKey}&location=${longitude},${latitude}`,
					method: 'GET',
					success: (res) => {
						clearTimeout(timer);
						if (res.data.status) {
							uni.hideLoading()
							let address = res.data.regeocode.formatted_address;
							callback && callback.call(undefined, {
								longitude: longitude,
								latitude: latitude,
								address: address,
								locationMode: locationMode,
								speed: speed
							})

						} else {
							uni.hideLoading()
							//地址转换失败
							callback && callback.call(undefined, {
								longitude: longitude,
								latitude: latitude,
								address: "地址转换失败" + res.data.status,
								locationMode: locationMode,
								speed: speed
							})
						}
					},
					fail: (err) => {
						clearTimeout(timer);
						uni.hideLoading()
						callback && callback.call(undefined, {
							longitude: longitude,
							latitude: latitude,
							address: "地址转换失败" + err.errMsg,
							locationMode: locationMode,
							speed: speed
						})
					}
				})
			}
		},
		fail: (err) => {
			clearTimeout(timer);
			uni.hideLoading()
			//未获取定位
			callback && callback.call(undefined, {
				longitude: "",
				latitude: "",
				address: "获取定位失败",
				locationMode: "手机定位",
				errCode: "200"
			})
		}
	});
}

export const uuid = () => {
	return "file" + Math.floor(Math.random() * 60 * 24) + new Date().getTime()
}


export const formatDate = (iDate, sFormat = 'yyyy-MM-dd HH:mm:ss') => {
	if (!iDate) {
		return '';
	}
	let dDate = new Date(iDate);
	let year = dDate.getFullYear(); // 年
	let month = dDate.getMonth() + 1; // 月
	if (month < 10) {
		month = '0' + month;
	}
	let date = dDate.getDate(); // 日
	if (date < 10) {
		date = '0' + date;
	}
	let hour = dDate.getHours(); // 时
	if (hour < 10) {
		hour = '0' + hour;
	}
	let minute = dDate.getMinutes(); // 分
	if (minute < 10) {
		minute = '0' + minute;
	}
	let second = dDate.getSeconds(); // 秒
	if (second < 10) {
		second = '0' + second;
	}
	let millisecond = dDate.getMilliseconds(); // 毫秒
	if (sFormat.indexOf('yyyy') >= 0) {
		sFormat = sFormat.replace('yyyy', year + '');
	}
	if (sFormat.indexOf('MM') >= 0) {
		sFormat = sFormat.replace('MM', month + '');
	}
	if (sFormat.indexOf('dd') >= 0) {
		sFormat = sFormat.replace('dd', date + '');
	}
	if (sFormat.indexOf('HH') >= 0) {
		sFormat = sFormat.replace('HH', hour + '');
	}
	if (sFormat.indexOf('mm') >= 0) {
		sFormat = sFormat.replace('mm', minute + '');
	}
	if (sFormat.indexOf('ss') >= 0) {
		sFormat = sFormat.replace('ss', second + '');
	}
	if (sFormat.indexOf('SSS') >= 0) {
		sFormat = sFormat.replace('SSS', millisecond + '');
	}
	return sFormat;
};

//防抖函数
export const debounce = (func, delay = 1500) => {
	let timer = null
	return function(...args) {
		if (timer !== null) {
			clearTimeout(timer)
		}
		timer = setTimeout(function() {
			func.apply(this, args)
		}, delay)
	}
}

export const getDurations = (milliseconds) => {

	// hours
	const hours = milliseconds / 1000 / 60 / 60
	const hoursRound = Math.floor(hours)
	const hoursStr = `${hoursRound > 0 ? `${hoursRound}时` : ''}`
	// minutes
	const minutes = milliseconds / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound)
	const minutesRound = Math.floor(minutes)
	const minutesStr = `${minutesRound > 0 ? `${minutesRound}分` : ''}`
	// seconds
	const seconds = milliseconds / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound)
	const secondsRound = Math.floor(seconds)




	return str
}

// 预览图片
export const previewImage = async (option, callback) => {
	let map = {
		"uuid": option
	}

	const res = await myRequest({
		url: "/api/v1/systemfiles/previewfileList",
		data: map
	})
	console.log(res.data.data)
	if (res.data.status == "succeed") {
		let list = []
		let resList = res.data.data
		let previewList = []
		resList.forEach(async (e) => {
			previewList.push(e.data)
			if (e.dataType == "netUrl") {
				list.push(e.data)
			} else {
				const dataRes = await base64ToPath(e.data);
				list.push(dataRes)
			}
		})
		callback && callback.call(undefined, {
			downloadList: list,
			previewList: previewList
		})
	} else {
		uni.showToast({
			duration: 2000,
			title: "预览失败",
			icon: "error"
		})
	}
}

//表格数据处理
export const preDispose = (columnData, listData) => {
	//接收传过来表头数据，行数据
	//行数据经处理后
	//columnData标识哪些需要合并的列
	let preColumnDataMap = columnData.reduce((prev, item) => {
		if (item.isMergeCol === 1) {
			prev['mergeColomnData'].push(item.prop)
		} else {
			prev['noMergeColumnData'].push(item.prop)
		}
		return prev
	}, {
		mergeColomnData: [],
		noMergeColumnData: []
	})
	let mergeColomnData = preColumnDataMap.mergeColomnData
	let noMergeColumnData = preColumnDataMap.noMergeColumnData
	//如果不存在需要合并的列则直接返回
	if (mergeColomnData.length == 0) {
		return listData
	}
	//如果存在需要合并的列则需要处理，处理后的数据结构应该为{...合并的列的键值，[无需合并的列的数组对象{},{}]}
	//创建一个新数组，为处理过后的listData的值
	let newListData = []
	newListData = listData.reduce((prev, item) => {
		let map = {}
		let noMergeMap = {}
		mergeColomnData.forEach((e) => {
			map[e] = item[e]
		})
		noMergeColumnData.forEach((e) => {
			noMergeMap[e] = item[e]
		})
		if (prev.length == 0) {
			map.noMergeList.push(noMergeMap)
			prev.push(map)
		} else {
			//获取上一个处理过后的对象
			let lastMap = prev[prev.length - 1];
			let compareValue = false;
			//需要判断当前和上一个的主map是否一致
			for (let i; i < mergeColomnData.length; i++) {
				let key = mergeColomnData[i]
				//一旦不相等就直接push进数组，否则就将compareValue变为true
				if (lastMap[key] != map[key]) {
					compareValue = false
					map.noMergeList.push(noMergeMap)
					prev.push(map)
					break;
				} else {
					compareValue = true
				}
			}
			if (compareValue) {
				prev[prev.length - 1].noMergeList.push(noMergeMap)

			}


		}
		return prev
	}, [])
	return newListData;
}


// 封装图片上传接口
// option为包含图片项的表单字段;
// fileMediaData为需要上传的图片字段数组
// callback为回调函数,其中返回uuid
export const uploadFile = async (option, fileMediaData, callback) => {
	if (typeof option == 'undefined' || option == null || Object.keys(option).length == 0) {
		console.error("请传入带有图片的表单数据")
	}
	if (typeof fileMediaData == 'undefined' || fileMediaData == null || fileMediaData.length == 0) {
		console.error("请输入需要上传的图片字段数组")
	}
	let fileArr = [];
	let uuidTypes = [];
	let fileKeys = fileMediaData;
	let submitForm = JSON.parse(JSON.stringify(option));
	Object.keys(submitForm).forEach((key) => {
		if (fileKeys.includes(key)) {
			let uuidArr = [];
			if (submitForm[key] && submitForm[key].length > 0) {
				submitForm[key].forEach((item) => {
					if (item.uuid) {
						let map = {};
						map.uri = item.url;
						uuidTypes.push(item.uuid);
						uuidArr.push(item.uuid.split(';')[0]);
						fileArr.push(map);
					}

				});
				submitForm[key] = uuidArr.join(';');
			}

		}
	});
	const res = await myFileRequest({
		url: '/api/v1/systemfiles/insertFilesReal',
		files: fileArr,
		formData: {
			uuidTypes: uuidTypes
		}
	}).catch((e) => {
		callback && callback.call(undefined, {
			uploadFileStatus: "failed",
			...submitForm
		})
	})
	callback && callback.call(undefined, {
		uploadFileStatus: res.data.status,
		...submitForm
	})
}
//base64转图片
export const dataURLtoTempPath = (dataurl) => {

	var arr = dataurl.split(',');
	var mime = arr[0].match(/:(.*?);/)[1];
	var bstr = atob(arr[1]);
	var n = bstr.length;
	var u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	//生成文件
	const blodData = new ArrayBuffer([u8arr], {
		type: mime
	});
	console.log(blodData, blodData)
	return URL.createObjectURL(blodData)

}

export const base64ToPath = (base64) => {
	//base64转文件路径
	return new Promise(function(resolve, reject) {
		try {
			var extName = base64.match(/data\:\S+\/(\S+);/)
			if (extName) {
				extName = extName[1]
			} else {
				throw new Error("Not base64");
			}
			var fileName = Date.now() + '.' + extName
			//app
			// #ifdef APP-PLUS
			if (typeof plus === 'object') {
				var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
				bitmap.loadBase64Data(base64, function() {
					var filePath = '_doc/uniapp_temp/' + fileName
					bitmap.save(filePath, {}, function() {
						bitmap.clear()
						resolve(filePath)
					}, function(error) {
						bitmap.clear()
						throw error;
					})
				}, function(error) {
					bitmap.clear()
					throw error;
				})
				return
			}
			// #endif
			// #ifdef H5
			if (typeof window === 'object' && 'document' in window) {
				base64 = base64.split(',')
				var type = base64[0].match(/:(.*?);/)[1]
				var str = atob(base64[1])
				var n = str.length
				var array = new Uint8Array(n)
				while (n--) {
					array[n] = str.charCodeAt(n)
				}
				return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
					type: type
				})))
			}
			// #endif
			// #ifdef MP-WEIXIN
			if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
				var filePath = wx.env.USER_DATA_PATH + '/' + fileName
				wx.getFileSystemManager().writeFile({
					filePath: filePath,
					data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
					encoding: 'base64',
					success: function() {
						resolve(filePath)
					},
					fail: function(error) {
						throw error
					}
				})
				return
			}
			// #endif
		} catch (e) {
			return resolve(base64);
		}
	})
}

export const previewImageList = uuid => {
	return new Promise(async (resolve, reject) => {
		const res = await myRequest({
			url: "/api/v1/systemfiles/previewfileList",
			data: {
				uuid: uuid
			}
		})
		console.log(res, 'res')
		if (res.data.status === 'succeed') {
			let fileList = []
			res.data.data.forEach((item, index) => {
				let base64 = item.data;
				if (item) {
					fileList.push({
						name: index,
						url: base64,
						extname: "png"
					})
				}
			})
			resolve(fileList)
		} else {
			reject(res.msg)
		}
	})
}

export const accDiv = (arg1, arg2) => {
	var t1 = 0,
		t2 = 0,
		r1,
		r2
	try {
		t1 = arg1.toString().split('.')[1].length
	} catch (e) {}
	try {
		t2 = arg2.toString().split('.')[1].length
	} catch (e) {}
	r1 = Number(arg1.toString().replace('.', ''))
	r2 = Number(arg2.toString().replace('.', ''))
	return (r1 / r2) * Math.pow(10, t2 - t1)
}